/**
 * excel数据导入api
 * @Author: pan.lu
 * @Date:   2019-06-29
 * @Project jz
 */
import request from "@/utils/request";
import {Message,Loading} from "element-ui";

const {getSetting} = window.systemParamsUtils;

let loading = null;

class BaseApi{
    module=''
    constructor(module){
        // 读取模块配置
        this.module=module;
    }

    /**
     * 获取树形表码数据
     * @param type
     * @param codeId
     */
    listTreeData(type,codeId) {
        return request({
            url: `/api/codetree/${type}/${codeId}`,
            method: "get",
            baseURL: this._getBaseURL(),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            }
        });
    }

    /**
     * 获取序列号
     * @param id     导入配置id
     * @param importSeq 导入序列号
     * @param file   excel文件
     * @param params 附加参数
     */
    nextSequence() {
        return request({
            url: "/excel-imports/seq",
            method: "get",
            baseURL: this._getBaseURL(),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            }
        });
    }

    /**
     * 获取最后一次导入文件列表
     * @param importSeq
     */
    fetchLastFileList(importSeq) {
        return request({
            url: "/excel-imports/files/"+importSeq,
            method: "get",
            baseURL: this._getBaseURL(),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            }
        });
    }

    /**
     * excel文件导入
     * @param id     导入配置id
     * @param importSeq 导入序列号
     * @param clientId 客户端文件id
     * @param file   excel文件
     * @param params 附加参数
     */
    importExcel(id, importSeq, clientId, file, params = {}) {
        let formData = new FormData()
        formData.append("file", file);
        formData.append("params", new Blob([JSON.stringify(params || {})], {type: "application/json"}));
        return request({
            url: "/excel-imports/" + id + "/" + importSeq + "/" + clientId,
            method: "post",
            data: formData,
            baseURL: this._getBaseURL(),
            timeout: 600000,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });
    }

    /**
     * excel获取导入统计信息
     * @param id     导入配置id
     * @param importSeq 导入序列号
     */
    getImportStat(id,importSeq) {
        return request({
            url: `/excel-imports/stat/${id}/${importSeq}`,
            method: "get",
            baseURL: this._getBaseURL(),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            }
        });
    }

    /**
     * 加载进度条
     * @param id
     * @param importSeq
     * @param timeout
     */
    loadUploadProcess(id, importSeq) {
        return request({
            url: "/excel-imports/process/" + id + "/" + importSeq,
            method: "get",
            baseURL: this._getBaseURL(),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
        })
    }

    /**
     * 载导入模板
     * @param id 导入配置id
     * @param fileName 导出模板文件名称
     * @returns {*}
     */
    downloadTemplate(id, fileName) {
        loading = Loading.service({
            lock: true,
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.8)",
            text: "模板下载中，请稍后..."
        });
        return request({
            url: "/excel-imports/templates/" + id + "/_excel",
            method: "get",
            baseURL: this._getBaseURL(),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
            responseType: 'arraybuffer'
        }).then(response => {
            this._download(response.data, fileName)
        }).catch(() => {
            Message.error('下载模板文件出错！');
            loading && loading.close();
        });
    }

    /**
     * 获取最后导入数据的批次号
     * @param id 导入配置id
     */
    getLastImportSeq(id) {
        return request({
            url: "/excel-imports/lasts/" + id,
            method: "get",
            baseURL: this._getBaseURL()
        });
    }

    /**
     * 获取列表显示配置信息
     * @param id 导入配置id
     */
    getImportConfig(id) {
        return request({
            url: "/excel-imports/configs/" + id,
            method: "get",
            baseURL: this._getBaseURL()
        });
    }

    /**
     * 批量更新缓存表数据
     * @param id 导入配置id
     * @param importSeq 导入序列号
     * @param data 批量修改数据数组
     * @param params 附加参数
     */
    update(id, importSeq, data = [], params = {}) {
        let updateVo = {
            data: data,
            params: params
        };
        return request({
            url: "/excel-imports/" + id + "/" + importSeq,
            method: "put",
            baseURL: this._getBaseURL(),
            data: updateVo,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
            },
        });
    }

    /**
     * 删除导入文件并清空对应数据
     * @param id    导入配置id
     * @param importSeq 导入序列号
     * @param uploadId   文件id
     * @param params 附加参数
     */
    deleteFile(id, importSeq, uploadId, params = {}) {
        return request({
            url: `/excel-imports/${id}/${importSeq}/files/${uploadId}/_clean`,
            method: "put",
            baseURL: this._getBaseURL(),
            data: params,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
        });
    }

    /**
     * 批量删除缓存表数据
     * @param id    导入配置id
     * @param importSeq 导入序列号
     * @param ids   批量删除rowIndex数组
     * @param params 附加参数
     */
    delete(id, importSeq, ids = [], params = {}) {
        let idsVo = {
            ids: ids,
            params: params
        };
        return request({
            url: "/excel-imports/" + id + "/" + importSeq + "/_clean",
            method: "put",
            baseURL: this._getBaseURL(),
            data: idsVo,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
        });
    }

    /**
     * 清空缓存表中所有错误数据
     * @param id    导入配置id
     * @param importSeq 导入序列号
     * @param params    附加参数
     */
    cleanErrorData(id, importSeq, params = {}) {
        return request({
            url: "/excel-imports/" + id + "/" + importSeq + "/_clean-all",
            method: "put",
            baseURL: this._getBaseURL(),
            data: params,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
        });
    }

    /**
     * 导出缓存表所有无效数据
     * @param id    导入配置id
     * @param importSeq 导入序列号
     * @param fileName 导出excel文件名
     * @returns {*}
     */
    exportErrorData(id, importSeq, fileName) {
        loading = Loading.service({
            lock: true,
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.8)",
            text: "数据导出中，请稍后..."
        });
        return request({
            url: "/excel-imports/invalid/" + id + "/" + importSeq + "/_excel",
            method: "get",
            baseURL: this._getBaseURL(),
            timeout: 600000,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
            responseType: 'arraybuffer'
        }).then(response => {
            this._download(response.data, fileName)
        }).catch(() => {
            Message.error('导出数据出错！');
            loading && loading.close();
        });
    }

    /**
     * 导入选择的数据到业务表
     * @param id    导入配置id
     * @param importSeq 导入序列号
     * @param ids   批量导入rowIndex数组
     * @param params 附加参数
     */
    importSelect(id, importSeq, ids = [], params = {}) {
        let idsVo = {
            ids: ids,
            params: params
        };
        return request({
            url: "/excel-imports/persistence/" + id + "/" + importSeq,
            method: "post",
            baseURL: this._getBaseURL(),
            data: idsVo,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
        });
    }

    /**
     * 导入所有有效的数据到业务表
     * @param id    导入配置id
     * @param importSeq 导入序列号
     * @param params 附加参数
     */
    importAll(id, importSeq, params = {}) {
        return request({
            url: "/excel-imports/persistence/" + id + "/" + importSeq + "/_all",
            method: "post",
            baseURL: this._getBaseURL(),
            data: params,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
            // 一小时
            timeout:3600000,
        });
    }

    /**
     * 下载二进制文件
     * @param data
     * @private
     */
    _download(data, fileName) {
        if (!data) {
            return;
        }
        let url = window.URL.createObjectURL(new Blob([data]));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        loading && loading.close();
    }

    /**
     * 根据module获取上下文
     * @private
     */
    _getBaseURL() {
        let apiModule = this.module;
        if (this.module === "" || !this.module) {
            apiModule = "BASE_API";
        }
        return getSetting(apiModule);
    }
}

export default BaseApi;
